package base.standard;

import base.standard.constant.ErrorCode;
import base.standard.exception.SimpleException;
import base.bean.StandardResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Global exception advice
 *
 * @description: 全局异常处理
 * @author: cyj
 * @date 2020 -10-15 17:00:36
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionAdvice {

    /**
     * Simple exception handle response entity
     *
     * @param e e
     * @return the response entity
     * @description:
     */
    @ExceptionHandler(value = SimpleException.class)
    public ResponseEntity simpleExceptionHandle(SimpleException e) {
        StandardResponse standardResponse = new StandardResponse(e.getMessage(), e.getCode());
        ResponseEntity<StandardResponse> responseEntity = new ResponseEntity<>(standardResponse, e.getHttpStatus());
        return responseEntity;
    }

    /**
     * Method argument not valid exception handle response entity
     *
     * @param e e
     * @return the response entity
     * @description:
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException e) {
        StringBuffer message = new StringBuffer();
        ErrorCode inParamsError = ErrorCode.IN_PARAMS_ERROR;
        e.getBindingResult().getAllErrors().stream().forEach(objectError ->
                message.append(objectError.getDefaultMessage() + ";"));
        StandardResponse standardResponse = new StandardResponse(
                String.format(inParamsError.message, message.toString()), inParamsError.code);
        ResponseEntity<StandardResponse> responseEntity = new ResponseEntity<>(standardResponse,
                inParamsError.httpStatus);
        return responseEntity;
    }

    /**
     * Simple exception handle response entity
     *
     * @param e e
     * @return the response entity
     * @description:
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity simpleExceptionHandle(Exception e) {
        e.printStackTrace();
        ErrorCode errorCode = ErrorCode.UNKNOW_ERROR;
        StandardResponse standardResponse = new StandardResponse(errorCode.message, errorCode.code);
        ResponseEntity<StandardResponse> responseEntity = new ResponseEntity<>(standardResponse, errorCode.httpStatus);
        return responseEntity;
    }
}
